package com.xc.erp.security.filter;

import com.xc.erp.common.utils.JwtUtil;
import com.xc.erp.common.utils.RedisCache;
import com.xc.erp.modules.erp.domain.dto.LoginUser;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 过滤器
 *
 * @author wjw 2022/10/18
 * @DateTime: 2022/10/18 8:57
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
        //获取token
        String token = request.getHeader("token");

        if (!StringUtils.hasText(token)) {
            //请求没有携带token，放行
            filterChain.doFilter(request, response);
            return;
        }

        //解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            //获取 userId
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        // 从Redis中获取用户信息
        LoginUser loginUser = (LoginUser) redisCache.getCacheObject("login:" + userid);
        // 判断LoginUser是否为空，为空说明未登录
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        // 如果存在把用户信息存入SecurityContextHolder 对象中
        // 补充权限信息
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }

}
